import Koa from 'koa'
import Router from 'koa-router'
import { Sequelize,DataTypes,Op } from 'sequelize'
import bodyParser from 'koa-bodyparser'
import cors from '@koa/cors'

const app = new Koa()
const router=new Router()

app.use(cors())

app.use(bodyParser())

const sequelize =new Sequelize('bookDb','root','123456',{
    dialect:'mysql',
    host:'localhost'
})

let Book = sequelize.define('books',{
    bookName:DataTypes.STRING,
    author:DataTypes.STRING
})

// await sequelize.sync({force:true})

// await Book.bulkCreate([
//     {
//         bookName:'西游记',
//         author:'吴承恩'
//     },
//     {
//         bookName:'红楼梦',
//         author:'曹雪芹'
//     },
//     {
//         bookName:'水浒传',
//         author:'施耐庵'
//     },
//     {
//         bookName:'三国演义',
//         author:'罗贯中'
//     },
// ])


router.get('/book',async (ctx)=>{
    let keyword = ctx.request.query.keyword || ''
    let reslut;
    if (keyword) {
        reslut = await Book.findAll(
            {
                where:{
                    [Op.or]:{
                        bookName:{
                            [Op.like]:`%${keyword}%`
                        },
                        author:{
                            [Op.like]:`%${keyword}%`
                        },
                    }
                }
            }
        )
    }else{
        reslut = await Book.findAll()
    }
   
    ctx.body={
        code:1000,
        data:reslut,
        msg:"查询成功"
    }
})
router.get('/book/:id',async (ctx)=>{
    let id = ctx.params.id || 0
    let book = await Book.findByPk(id)
    ctx.body={
        code:1000,
        data:book,
        msg:"查询成功"
    }
})
router.post('/book',async (ctx)=>{
    let obj = ctx.request.body
    let book = await Book.create(obj)
    ctx.body={
        code:1000,
        data:book,
        msg:"新增成功"
    }
})
router.put('/book/:id',async (ctx)=>{
    let id =ctx.params.id || 0
    let obj = ctx.request.body
    console.log(obj);
    
    let book = await Book.update(obj,{where:{id}})
    ctx.body={
        code:1000,
        data:book,
        msg:"修改成功"
    }
})
router.delete('/book/:id',async (ctx)=>{
    let id = ctx.params.id || 0
    let book = await Book.destroy({where:{id}})
    ctx.body={
        code:1000,
        data:book,
        msg:"删除成功"
    }
})

app.use(router.routes())

let port = 3000
app.listen(port)

console.log(`http://localhost:${port}`);
